#生成现有病人简报

import win32com.client
import datetime
import os
import re
from multiprocessing.dummy import Pool
import pandas as pd
from docx import Document
from docx.oxml.ns import qn
import shift_rec
# def get_desktop():
#     return os.path.join(os.path.expanduser('~'), 'Desktop')


def xls_to_xlsx(filename):
    excel_exe = win32com.client.gencache.EnsureDispatch('Excel.Application')
    wb = excel_exe.Workbooks.Open(filename)
    new_name = f"{filename}x"
    wb.SaveAs(new_name, FileFormat=51)
    wb.Close()
    excel_exe.Application.Quit()
    return new_name


def p_l_generater(xlsx_filename):
    df = pd.read_excel(
        xlsx_filename,
        sheet_name='Sheet1',
        usecols=['住院号', '床号', '姓名', '性别', '年龄', '入院日期', 'DIAGNOSES', '出院日期'],
    )

    df['入院日期'] = pd.to_datetime(df['入院日期'])

    df['入院'] =df['入院日期'].dt.strftime("%m.%d")
    
    df['入院日期'] = df['入院日期'].dt.date
    
    df['天数'] = datetime.date.today() - df['入院日期']
    df['天数'] = df['天数'].dt.days.astype(str)+"天"
    df['病人'] = df['床号'].str.cat([
        df['姓名'], 
        df['性别'], 
        df['年龄'],
     
        # df['入院'],
     
        # df['天数'],
   

                    ],sep=' ')
    df['病人']= df['病人']+'  '+df['入院']+"("+df['天数']+") " + df['住院号'].astype(str)
    df1 = df.loc[
        df['出院日期'].isna(),
        ['住院号','床号','病人', 'DIAGNOSES']].sort_values(
            by='床号')
    df1 = df1.reset_index(drop=True)
    df1.index += 1
    df1 = df1.loc[:, ['住院号','病人', 'DIAGNOSES']]
    doc = Document()
    
    
    result = df1.to_dict(orient='records')
    idx = 1
    for each in result:
        pid = each['住院号']
        patient = each['病人']
        diag = each['DIAGNOSES']
        query_app = shift_rec.AcquireInfoTotal(pid)
        query_list = ['病程记录', 'LIS报告单', 'PACS报告单']
        pool = Pool(3)
        query_result = pool.map(query_app.query_content, query_list)
        query_dic = {}
        for each_result in query_result:
            query_dic.update(each_result)
        data_resolved = shift_rec.DataResolver(query_app.pid)
        data_resolved.record_resolve(query_dic)

        if data_resolved.patient_info:
            patient_info = data_resolved.patient_info

        chief_complaint = patient_info['主诉']
        test_res = patient_info['化验单']

        test_result = ""
        for name, unit, sx in [
            ["肺炎支原体", "[Au/mL]*", "支(20)"],              
            ["肺炎衣原体", "[Au/mL]*", "衣(20)"],
            ["25：", "ng/ml", "VD"],
            ["降钙素原", "ng/ml", "PCT"],
            ["白细胞计数", "×10\^9/L", "WBC"],
        ]:
            result = re.search(f"{name}.*?([0-9.阳阴性]+)\s{unit}", test_res)

            if result:
                
                test_result += f"{sx} {result.group(1)}；"
        
        image_res = patient_info['影像学']
        p = doc.add_paragraph()
        p.add_run(f"【{idx}】{patient}").bold=True
        p.add_run('\n主诉：'+ chief_complaint+"。 诊断："+diag)
        p.add_run('\n'+ test_result+image_res)
        idx += 1
    doc.styles["Normal"].font.name = 'Times New Roman'
    doc.styles["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
    
    doc.save('done.docx')
    os.startfile('done.docx')
    
    # df1.to_excel('done.xlsx',
    #              columns=['病人', 'DIAGNOSES'],
    #              index=True)

    # os.startfile('done.xlsx')


if __name__ == '__main__':
    if os.path.exists('E:\\RjDir\\ys\\Desktop\\住院病历.xlsx'):
        os.remove('E:\\RjDir\\ys\\Desktop\\住院病历.xlsx')
    p_l_generater(xls_to_xlsx('E:\\RjDir\\ys\\Desktop\\住院病历.xls'))
